package com.posjiajia.user.operator.controller;

import com.posjiajia.user.core.bo.UserBo;
import com.posjiajia.user.core.vo.UserVo;
import com.posjiajia.user.operator.contant.UserOperatorContant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zhenhua.sun
 * @title com.posjiajia.user.operator.controller
 * @date 8/28/16
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserBo userBo;

    /**
     * 登录
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public String login(String userName, String password, HttpServletRequest request, HttpServletResponse response){
        UserVo userVo;
        try {
            userVo = userBo.login(userName,password,null);
        }catch (Exception e){
            logger.error("user login error,userName:{}",userName);
            return "redirect:/login/tologin";
        }
        String referer = request.getHeader("Referer");
        if (!StringUtils.isEmpty(referer) && !referer.contains("login")){
            return "redirect:"+referer;
        }
        request.setAttribute("userVo",userVo);
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("userVo",userVo);
        httpSession.setAttribute(UserOperatorContant.ISLOGIN,"ok");

        Cookie cookie = new Cookie("userToken",userVo.getUserToken());
        cookie.setPath("/");
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);
        return "redirect:/index";
    }

}
